package com.integrationpath.mengine.webapp.action;

import com.opensymphony.xwork2.Preparable;
import com.integrationpath.mengine.service.GenericManager;
import com.integrationpath.mengine.model.LinkType;
import com.integrationpath.mengine.webapp.action.BaseAction;

import java.util.List;

public class LinkTypeAction extends BaseAction implements Preparable {
    private GenericManager<LinkType, Integer> linkTypeManager;
    private List linkTypes;
    private LinkType linkType;
    private Integer  id;

    public void setLinkTypeManager(GenericManager<LinkType, Integer> linkTypeManager) {
        this.linkTypeManager = linkTypeManager;
    }

    public List getLinkTypes() {
        return linkTypes;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String linkTypeId = getRequest().getParameter("linkType.id");
            if (linkTypeId != null && !linkTypeId.equals("")) {
                linkType = linkTypeManager.get(new Integer(linkTypeId));
            }
        }
    }

    public String list() {
        linkTypes = linkTypeManager.getAll();
        return SUCCESS;
    }

    public void setId(Integer  id) {
        this. id =  id;
    }

    public LinkType getLinkType() {
        return linkType;
    }

    public void setLinkType(LinkType linkType) {
        this.linkType = linkType;
    }

    public String delete() {
        linkTypeManager.remove(linkType.getId());
        saveMessage(getText("linkType.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (id != null) {
            linkType = linkTypeManager.get(id);
        } else {
            linkType = new LinkType();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (new Integer(linkType.getId()) == null);

        linkTypeManager.save(linkType);

        String key = (isNew) ? "linkType.added" : "linkType.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}